package ch.upndown.upndown;

import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import java.util.List;

import ch.upndown.upndown.database.DatabaseAccess;
import ch.upndown.upndown.model.Website;
import ch.upndown.upndown.utils.UrlValidater;

/**
 * Created by DonMiguel on 30.07.2014.
 */
public class OverviewFragment extends ListFragment {
    private DatabaseAccess myDb;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myDb = DatabaseAccess.getInstance(getActivity());
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        loadWebsites();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public void loadWebsites() {
        List<Website> websites = myDb.getWebsites();
        setListAdapter(new OverviewAdapter(getActivity(), websites));
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        setEmptyText(getText(R.string.no_websites));
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_overview, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add_website:
                addWebsite();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void addWebsite() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View dialogContent = inflater.inflate(R.layout.dialog_add_website, null);
        builder.setView(dialogContent);
        builder.setTitle(R.string.add_website);
        builder.setPositiveButton(R.string.save_website, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton(R.string.cancel,null);

        AlertDialog dialog = builder.create();
        dialog.show();
        Button myButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        myButton.setOnClickListener(new UrlValidater(dialog, getActivity(), this));
    }
}
